package com.dimples.security.handler;

import com.dimples.common.constant.DimplesConst;
import com.dimples.common.util.CommonUtil;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * 权限不足处理器
 * 有@ExceptionHandler时会失效, 去@ExceptionHandler中捕获
 *
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2021/6/27
 */
@Configuration
public class DimplesAuthenticationAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        if (CommonUtil.isAjaxRequest(request)) {
            response.setContentType(DimplesConst.JSON_UTF8);
            JSONObject result = new JSONObject();
            result.set("code", HttpServletResponse.SC_UNAUTHORIZED);
            result.set("msg", "没有该权限！");
            response.getWriter().write(JSONUtil.toJsonStr(result));
        }
    }
}
